//
//  LTCitySceneryController.m
//  LocalTravelIPhone
//
//  Created by zheng ji on 14-3-28.
//  Copyright (c) 2014年 jxw. All rights reserved.
//
#define RecordsOfPage 20
#import "LTCitySceneryController.h"

@interface LTCitySceneryController ()
{
    CLLocationManager *_currentLoaction;
    
    NSUserDefaults *myDefaults;
    UICollectionView* _collectionView;

    double _currentPostionlatitude;
    double _currentPostionlongitude;
    NSString* _currentCityID;//当前城市ID
    UILabel *_loadMoreTip;//加载更多的提示
    UIActivityIndicatorView	*_activityView;
    LTAppDelegate* _appDelegate;

    
    NSMutableArray* _arrayScenery;
}
@end

@implementation LTCitySceneryController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _appDelegate=[[UIApplication sharedApplication] delegate];
     myDefaults=[NSUserDefaults standardUserDefaults];
    
    self.navigationItem.title=@"获取当前城市...";
    [self startGetLocation];
    [self createCollectionView];
    // Do any additional setup after loading the view.
}
-(void)createCollectionView{
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize=CGSizeMake(134,152);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    _collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
    
    
    [_collectionView registerNib:[UINib nibWithNibName:@"CollectionCell" bundle:nil] forCellWithReuseIdentifier:@"CollectionCell"];
   // [_collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"CollectionCell"];
    
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    _collectionView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_collectionView];
}
-(void)stopActivityIndicatorView{
    [_activityView stopAnimating];
    _loadMoreTip.hidden=YES;
}
-(void)createActivityIndicatorView{
    _activityView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityView.hidesWhenStopped=YES;
    
    CGRect activityFrame=_activityView.frame;
    activityFrame.origin.x=self.view.frame.size.width/2-50;
    activityFrame.origin.y=self.view.frame.size.height/2;
    
    [_activityView setFrame:activityFrame];
    
    _activityView.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
    
    
    
    _loadMoreTip=[[UILabel alloc] initWithFrame:CGRectMake(activityFrame.origin.x+30, activityFrame.origin.y+5, 100, 20)];
    
    _loadMoreTip.textAlignment=NSTextAlignmentCenter;
    
    _loadMoreTip.text=@"正在加载数据";
    _loadMoreTip.textColor=[UIColor redColor];
    _loadMoreTip.font=[UIFont systemFontOfSize:16];
    _loadMoreTip.backgroundColor=[UIColor clearColor];
    
    [self.view addSubview:_activityView];
    [self.view addSubview:_loadMoreTip];
    [_activityView startAnimating];
    _activityView.hidden=NO;
    _loadMoreTip.hidden=NO;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _currentCityID=@"53";
    [self searchSceneryByCityID:_currentCityID page:1 pageSize:20];
}
-(void)startGetLocation{
    _currentLoaction = [[CLLocationManager alloc] init];
    _currentLoaction.delegate = self;
    
    _currentLoaction.distanceFilter = 1000;
    
    _currentLoaction.desiredAccuracy = kCLLocationAccuracyBest;
    [_currentLoaction startUpdatingLocation];
}

-(void) checkVersionTimer:(NSTimer*)theTimer{
    [self checkVersion];
    [theTimer invalidate];
}



-(void)checkVersion{
    
    if([CommonConfigUtil checkVersion]){
        
        NSString *versionNumber=[myDefaults objectForKey:@"versionNumber"];
        NSString *appUrl=[myDefaults objectForKey:@"appUrl"];
        // NSString *appCommentUrl=[myDefaults objectForKey:@"appCommentUrl"];
        NSString *description=[myDefaults objectForKey:@"description"];
        
        if(nil==appUrl)appUrl=@"";
        if(nil==versionNumber)versionNumber=@"";
        if(nil==description)description=@"";
        
        
        if(![@"" isEqualToString:appUrl] && nil!=versionNumber&& ![@"" isEqualToString:versionNumber]&& [versionNumber compare: [CommonConfigUtil getCurrVersion] ]==NSOrderedDescending ){
            
            
            NSString *strMessge;
            if(nil!=description&&![@"" isEqualToString:description]){
                strMessge=[NSString stringWithFormat:@"%@版本发布啦！%@",versionNumber,description];
            }else{
                strMessge=[NSString stringWithFormat:@"%@版本发布啦！是否需要升级？",versionNumber];
            }
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本升级" message:strMessge                                                           delegate:self  cancelButtonTitle:@"立即升级" otherButtonTitles: @"忽略",nil];
            [alert setTag:1];
            
            [alert show];
            
            alert=nil;
        }
        
    }
    
}




- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if([alertView tag]==1&&buttonIndex == 0) {
        
        NSString *appUrl=  [myDefaults objectForKey:@"appUrl"];
        if(nil!=appUrl && ![@"" isEqualToString:appUrl]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrl]];
        }
        
    }
    
}



- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [_currentLoaction stopUpdatingLocation];
    
    _currentPostionlatitude=newLocation.coordinate.latitude;
    _currentPostionlongitude=newLocation.coordinate.longitude;
    BOOL  __block hasCity=NO;

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if(placemarks.count>0){
            CLPlacemark* _placeMark = [placemarks objectAtIndex:0];
            
            NSLog(@"%@",_placeMark.locality);
            self.navigationItem.title=_placeMark.locality;
            [self searchSceneryByCityName:_placeMark.locality];
            hasCity=YES;
        }
        // we have received our current location, so enable the "Get Current Address" button
    }];
    geocoder=nil;
    _currentLoaction=nil;
    if(!hasCity){
        //读取北京的景点
        
       
        // _currentCityID=@"53";
       // [self searchSceneryByCityID:_currentCityID page:1 pageSize:RecordsOfPage];
    }
}
-(void)searchSceneryByCityName:(NSString*)cityName{
    
    if([cityName hasSuffix:@"市"]) {
        cityName=[cityName substringToIndex:cityName.length -1];
    }
    NSString* cityID=[_appDelegate getCityIDByName:cityName];
    _currentCityID =cityID;
    [self searchSceneryByCityID:cityID page:1 pageSize:RecordsOfPage];
    
    
    
}
-(void)searchSceneryByCityID:(NSString*)cityID page:(int)page pageSize:(int)pageSize{
    NSDictionary* dict=[NSDictionary dictionaryWithObjectsAndKeys:cityID,@"cityID",[NSString stringWithFormat:@"%d",page],@"page",[NSString stringWithFormat:@"%d",pageSize],@"pageSize", nil];
    [self createActivityIndicatorView];
        [NSThread detachNewThreadSelector:@selector(searchSceneryByCityIDInBackgroud:) toTarget:self withObject:dict];
}

-(void)searchSceneryByCityIDInBackgroud:(NSDictionary*)dict{
    
    if(![CommonConfigUtil checkNetworkReachable]) return ;
    NSString* cityID=[dict objectForKey:@"cityID"];
    NSString* page=[dict objectForKey:@"page"];
    NSString* pageSize=[dict objectForKey:@"pageSize"];
    
    NSString* xmlData= [LocalTravelRequest getSceneryListByCityId:cityID page:[page intValue] pageSize:[pageSize intValue]];
    [self parseData:xmlData  cityID:_currentCityID];
        
        
    
    
}
-(void) parseData:(NSString*)xmlData cityID:(NSString*)cityID{
    SceneryListParse* parse=[[SceneryListParse alloc]initWithXmlData:xmlData];
    
    _arrayScenery=[parse getScenaryList];
    parse=nil;
    [_collectionView reloadData];
    
    if(_arrayScenery==nil || _arrayScenery.count==0){
        _loadMoreTip.hidden=NO;
        _loadMoreTip.text=@"未找到景点数据！";
        
    }else{
        
        
        _loadMoreTip.hidden=YES;
        
        
        
    }
}


//是否成功获取当前位置
-(BOOL)hasCurrentLocation{
    if(_currentPostionlongitude>0) return YES;
    return NO;
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if(_arrayScenery !=nil) return _arrayScenery.count;
    
    return 0;
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
    if(_arrayScenery !=nil && _arrayScenery.count>indexPath.row){
        NSDictionary* dict=[_arrayScenery objectAtIndex:indexPath.row];
        cell.lblTitle.text=[dict objectForKey:@"sceneryName"];
        cell.lblPrice.text=[NSString stringWithFormat:@"最低价:¥ %@",[dict objectForKey:@"amountAdv"]];
        
        
       // cell.imageView.imageUrl=[dict objectForKey:@"imgPath"];
       NSString* imageName=[dict objectForKey:@"imgPath"];
        
               NSString* netImagePath=[NSString stringWithFormat:@"%@100_75/%@",[CommonConfigUtil getTongChenImageBaseUrl],imageName];
        cell.imageView.imageUrl=netImagePath;
        //cell.imageView.im
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(_arrayScenery ==nil || _arrayScenery.count<indexPath.row) return ;
   
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(15, 15, 15, 15);
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
